package com.whisperly.echotalk.bllmodel;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.netWorkUtils.BlinkCallback;
import com.whisperly.echotalk.starryb.netWorkUtils.NetworkUtils;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.Flash;
import com.whisperly.echotalk.starryb.utils.GlobalData;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ClientClear extends AppCompatActivity {

    private Toast currentToast;
    private View loadingView;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.client_clear);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        AppsManager.addActivity(this);

        ImageButton btnClearConversations = findViewById(R.id.btn_clear_conversations);
        btnClearConversations.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.animate().scaleX(0.8f).scaleY(0.8f).setDuration(100).withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        v.animate().scaleX(1f).scaleY(1f).setDuration(100);
                        if (GlobalData.getUsername().equals("")) {
                            showRegistrationAlertDialog();
                        } else {
                            showClearAlertDialog(getString(R.string.Clear_the_conversation_cache), getString(R.string.Note_carefully));

                        }
                    }
                });
            }
        });

        ImageButton btnClearHistory = findViewById(R.id.btn_clear_history);
        btnClearHistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.animate().scaleX(0.8f).scaleY(0.8f).setDuration(100).withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        v.animate().scaleX(1f).scaleY(1f).setDuration(100);
                        if (GlobalData.getUsername().equals("")) {
                            showRegistrationAlertDialog();
                        } else {
                            showClearAlertDialog(getString(R.string.Clear_usage_records), getString(R.string.Please_carefully));
                        }
                    }
                });
            }
        });

    }

    private void showRegistrationAlertDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_is_required)
                .setMessage(R.string.login_is_required_message)
                .setPositiveButton(R.string.login, (dialog, which) -> {
                    dialog.dismiss();
                    Intent intent = new Intent(this, Login.class);
                    startActivity(intent);
                    AppsManager.finishAll();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void showClearAlertDialog(String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title)
                .setMessage(message)
                .setPositiveButton(R.string.Know, (dialog, which) -> {
                    clearData(title);
                    dialog.dismiss();
                }).setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss()).setCancelable(false)
                .show();
    }

    private void clearData(String dataType) {
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(()->{
            if (dataType.equals(getString(R.string.clear_the_conversation_cache))) {
                if (GlobalData.getUser() != null && GlobalData.getUser().getObjectId() != null) {
                    String userId = GlobalData.getUser().getObjectId();
                    ClearClientDto clearClientDto = new ClearClientDto();
                    ChatHistory chatHistory = new ChatHistory();
                    chatHistory.setUserId(userId);
                    clearClientDto.setChatHistory(chatHistory);
                    clearClientDto.setType(1);
                    NetworkUtils.deleteBatch(clearClientDto,new BlinkCallback(){
                        @Override
                        public void onSuccess(ResultBody<?> response) {
                            if (response.getCode() == 200){
                                CommonResponse data = (CommonResponse) response.getData();
                                if (data.getSuccess()){
                                    if (currentToast != null) {
                                        currentToast.cancel();
                                    }
                                    Flash.setFlag(true);
                                    currentToast = Toast.makeText(ClientClear.this, R.string.The_conversation_history_has_been_cleared, Toast.LENGTH_SHORT);
                                    currentToast.show();
                                }
                            }
                            hideLoading();
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            Log.e("clearData-throwable", throwable.toString());
                            if (currentToast != null) {
                                currentToast.cancel();
                            }
                            currentToast = Toast.makeText(ClientClear.this, R.string.Network_error, Toast.LENGTH_SHORT);
                            currentToast.show();
                        }
                    });
                }
            }else if (dataType.equals(getString(R.string.Clear_usage_records))) {
                if (GlobalData.getUser() != null && GlobalData.getUser().getObjectId() != null) {
                    String userId = GlobalData.getUser().getObjectId();
                    ClearClientDto clearClientDto = new ClearClientDto();
                    ChatHistory chatHistory = new ChatHistory();
                    chatHistory.setUserId(userId);
                    clearClientDto.setChatHistory(chatHistory);
                    clearClientDto.setType(2);
                    NetworkUtils.deleteBatch(clearClientDto,new BlinkCallback(){
                        @Override
                        public void onSuccess(ResultBody<?> response) {
                            if (response.getCode() == 200){
                                CommonResponse data = (CommonResponse) response.getData();
                                if (data.getSuccess()){
                                    if (currentToast != null) {
                                        currentToast.cancel();
                                    }
                                    Flash.setFlag(true);
                                    currentToast = Toast.makeText(ClientClear.this, R.string.Usage_records_have_been_cleared, Toast.LENGTH_SHORT);
                                    currentToast.show();
                                }
                            }
                            hideLoading();
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            Log.e("clearData-throwable", throwable.toString());
                            if (currentToast != null) {
                                currentToast.cancel();
                            }
                            currentToast = Toast.makeText(ClientClear.this, R.string.Network_error, Toast.LENGTH_SHORT);
                            currentToast.show();
                        }
                    });
                }
            }else {
                hideLoading();
            }
        },1000);
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }
}
